package nina.yiyou.salary.output.util

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class CsvLineMaker {

  CsvLineMaker(List line) {
    _line = line
  }

  String make() {
    return _line
        .collect { toCsvCell(it) }
        .join(',')
  }

  private Object toCsvCell(Object rawValue) {
    if (rawValue == null || rawValue instanceof String) {
      return encodeStr(rawValue)
    }
    if (rawValue instanceof Double) {
      return rawValue.round(2)
    }
    if (rawValue instanceof LocalDateTime) {
      return rawValue.format(DATE_FMT)
    }
    return rawValue
  }

  private String encodeStr(String str) {
    if (!str) {
      return '=""'
    }

    try {
      Double.parseDouble(str)
      return "=\"${str}\""
    } catch (NumberFormatException ignored) {
      // 不是数字就走通用处理
    }

    return '"' + str
        .replace('\"', '\"\"')
        .replace('\r', '')
        .replace('\n', '\r\n') + '"'
  }

  private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy/M/d")

  private final List _line
}
